<template>
  <div style="display: flex; justify-content: space-between; align-items: center;">
    <div class="pefStyle">
      <el-tag class="el-icon-plus" color="#61649f" style="margin-right: 10px;width: 100px" @click="clickApiDlg">HTTP请求</el-tag>
      <el-tag class="el-icon-plus" color="#E6A23C" style="margin-right: 10px;width: 100px" @click="addController([],'if')">条件控制器</el-tag>
<!--      <el-tag class="el-icon-plus" color="#02A7F0FF" style="margin-right: 10px;width: 100px" @click="addController([],'for')">循环控制器</el-tag>-->
      <el-tag class="el-icon-plus" color="#7B4D12FF" style="margin-right: 10px;width: 100px" @click="addController([],'script')">自定义脚本</el-tag>
<!--      <el-tag class="el-icon-plus" color="#67C23AFF" style="margin-right: 10px;width: 100px" @click="addController([],'time')">等待控制器</el-tag>-->
      <el-tag class="el-icon-plus" color="#67C23AFF" style="margin-right: 10px;width: 100px" @click="addController([],'py')">导入PY脚本</el-tag>
    </div>
    <div style="margin-right: 10px;color: #606266">
      <el-tooltip content="场景运行权重设置，默认1设置后会影响运行权重，请谨慎设置！" :enterable="false" placement="top">
        <i class="el-icon-question" style="color: #909399; font-size: 18px;padding-right: 8px;cursor: pointer"></i>
      </el-tooltip>
      <el-input-number size="small" v-model="scenceData.weight" :min="1" :max="10" @change="handleChange" >
      </el-input-number>
    </div>
  </div>
  <el-scrollbar height="calc(100vh - 290px)">
    <el-tree
      :data="steps"
      :props="defaultProps"
      draggable
      :default-expand-all="isExpand"
      :expand-on-click-node="false"
      @node-click="handleStepClick"
      :allow-drop="allowDrop"
      @node-drop="updateStepOrder"
      :node-drag-start="handleDragScroll"
    >
      <template v-slot="{ node,data }">
        <el-card  v-if="data.stepInfo">
          <div slot="header" >
            <el-col :span="22">
              <div class="style">
                <!--HTTP接口展示-->
                <div v-if="data.stepInfo.type==='api'">
                  <span  slot="header" class="card-title">
                    <div style="font-weight: bold;margin-top: -15px">
                      <span class="icon" style="color: rgb(97, 100, 159)">{{ getCardIndex(node.parent, node) }}</span>
                      <el-tag color="#61649f" style="margin-right: 20px;height: 25px;font-size: 12px;line-height: 25px;">HTTP请求</el-tag>
                      <span style=" min-width: 60px;display: inline-block;">
                        <span v-if="data.stepInfo.content.method === 'POST'">
                          <b style="color: #49cc90;font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                        <span v-if="data.stepInfo.content.method === 'GET'">
                          <b style="color: #61affe;font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                        <span v-if="data.stepInfo.content.method === 'PUT'">
                          <b style="color: #fca130;font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                        <span v-if="data.stepInfo.content.method === 'PATCH'">
                          <b style="color: #50e3c2;font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                        <span v-if="data.stepInfo.content.method === 'DELETE'">
                          <b style="color: #f93e3e;font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                        <span v-if="data.stepInfo.content.method === 'DEAD'">
                          <b style="color: rgb(201, 233, 104);font-size: 15px">{{ data.stepInfo.content.method }}</b>
                        </span>
                      </span>
                    </div>
                    <b class="card-url">{{ data.stepInfo.content.url }}</b>
                    <span class="card-name">{{data.stepInfo.content.name }}</span>
                </span>
                </div>

                <!--if控制器展示-->
                <div v-if="data.stepInfo.type==='if'">
                <span slot="header" class="card-title">
                  <div style="margin-top: -15px">
                    <span class="icon" style="color: rgb(230, 162, 60);">{{ getCardIndex(node.parent, node) }}</span>
                    <el-tag color="rgb(230, 162, 60)" style="font-weight: bold; margin-right: 20px;height: 25px;font-size: 12px;line-height: 25px;">条件控制器</el-tag>
                    <span>
                      <el-input class="input-def" placeholder="变量，例如{{name}}" v-model="data.stepInfo.content.variable"/>
                      <el-select v-model="data.stepInfo.content.JudgmentMode" placeholder="请选择" size="small" style="margin-right: 8px;width: 100px">
                          <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                      </el-select>
                      <el-input class="input-def" placeholder="值" v-model="data.stepInfo.content.value"/>
                    </span>
                  </div>
                </span>
                </div>

                <!--循环控制器展示-->
                <div v-if="data.stepInfo.type==='for'">
                <span slot="header" class="card-title" >
                  <div style="margin-top: -15px">
                    <span class="icon" style="color: rgb(2, 167, 240)">{{ getCardIndex(node.parent, node) }}</span>
                    <el-tag color="rgb(2, 167, 240)" style="font-weight: bold; margin-right: 20px;height: 25px;font-size: 12px;line-height: 25px;">循环控制器</el-tag>
                    <el-radio-group v-model="data.stepInfo.content.select" @click.stop>
                      <el-radio label="count" value="count" >次数循环</el-radio>
                      <el-radio label="for" value="for">for循环</el-radio>
                      <el-radio label="while" value="while" disabled>while循环</el-radio>
                    </el-radio-group>
                  </div>
                </span>
                <div v-if="data.stepInfo.dlg" :key="data.id" @click.stop>
                <div v-if="data.stepInfo.content.select==='count' || data.stepInfo.content.select===''">
                  <div class="loop">
                    <span style="padding-right: 5px">循环次数</span>
                    <el-input v-model="data.stepInfo.content.cycleIndex" style="width: 200px" placeholder="循环次数" />
                    <span style="padding-right: 5px;padding-left: 10px">循环间隔</span>
                      <el-input-number
                        v-model="data.stepInfo.content.cycleInterval"
                        :min="0"
                        :max="999"
                        size="small"
                        controls-position="right"
                        placeholder="秒"
                      />
                    <span style="margin-left: 10px">秒</span>
                  </div>
                </div>
                <div v-if="data.stepInfo.content.select==='for'">
                  <div class="loop">
                    <el-input style="width: 200px" placeholder="定义变量名称" v-model="data.stepInfo.content.variableName"/>
                    <b style="margin-left: 10px;margin-right: 10px">in</b>
                    <el-input style="width: 200px" placeholder="变量，例如{{name}}" v-model="data.stepInfo.content.variable"/>
                    <span style="padding-right: 5px;padding-left: 10px">循环间隔</span>
                      <el-input-number
                        v-model="data.stepInfo.content.cycleInterval"
                        :min="0"
                        :max="999"
                        size="small"
                        controls-position="right"
                        placeholder="秒"
                      />
                    <span style="margin-left: 10px">秒</span>
                  </div>
                </div>
                <div v-if="data.stepInfo.content.select==='while'" ><div class="loop">敬请期待！</div></div>
                </div>
               </div>

                <!--自定义脚本展示-->
                <div v-if="data.stepInfo.type==='script'">
                <span slot="header" class="card-title">
                  <div style="margin-top: -15px" @click.stop>
                    <span class="icon" style="color: rgb(123, 77, 18)">{{ getCardIndex(node.parent, node) }}</span>
                    <el-tag color="rgb(123, 77, 18)" style="font-weight: bold; margin-right: 20px;height: 25px;font-size: 12px;line-height: 25px;">自定义脚本</el-tag>
                      <el-input @click.stop v-if="data.stepInfo.inputDlg" v-model="data.stepInfo.name" @blur="cancelEditing(data.stepInfo)" ref="input" maxlength="50"></el-input>
                      <el-button v-else class="script-button" plain type="text" @click="startEditing(data.stepInfo)" @click.stop>{{data.stepInfo.name}} <i class="el-icon-edit"></i></el-button>
                    </div>
                </span>
                <el-row :gutter="10" v-show="data.stepInfo.dlg" @click.stop>
                  <el-col :span="24" style="margin-top: 15px"><Editor v-model="data.stepInfo.script" lang="python" theme="chrome"></Editor></el-col>
                </el-row>
              </div>

                <!--time控制器展示-->
                <div v-if="data.stepInfo.type==='time'">
                <span slot="header" class="card-title">
                  <div style="margin-top: -15px">
                    <span class="icon" style="color: rgb(103, 194, 58)">{{ getCardIndex(node.parent, node) }}</span>
                    <el-tag color="rgb(103, 194, 58)" style="font-weight: bold; margin-right: 20px;height: 25px;font-size: 12px;line-height: 25px;">等待控制器</el-tag>
                      <el-input-number
                        v-model="data.stepInfo.content.time"
                        :min="0"
                        :max="999"
                        size="mini"
                        controls-position="right"
                        placeholder="秒"
                      >
                      </el-input-number>
                    <span style="margin-left: 10px">秒</span>
                  </div>
                </span>
              </div>
            </div>
            </el-col>
            <el-col :span="2">
              <span class="card-content" >
                <el-tooltip v-if="data.stepInfo.type==='api'" class="item" effect="light" content="接口任务运行权重默认为1,设置后将影响运行结果！" placement="top">
                  <el-input-number
                    @click.stop
                      v-model="data.stepInfo.weight"
                      :min="1"
                      :max="10"
                      size="mini"
                      controls-position="right"
                      placeholder=1
                      style="width: 80px;margin-right: 20px"
                    >
                  </el-input-number>
                </el-tooltip>
                <el-switch
                      @click.stop
                      v-model="data.stepInfo.status"
                      inline-prompt
                      size="small"
                      @click="switchClick(data)"
                      style="--el-switch-on-color: #53a8ff; --el-switch-off-color: #dcdfe6"
                    />
                <el-button @click.stop style="margin-left: 10px" size="mini" class="el-icon-delete" type="danger" @click="delTree(data)" circle />
              </span>
            </el-col>
          </div>
        </el-card>
      </template>
    </el-tree>
  </el-scrollbar>
  <!--  选择接口弹窗-->
  <apiCite v-if="addApiDlg" :selectType="selectType" @childEvent="addController" @close-modal="handleCloseModal"></apiCite>
  <!--  编辑接口弹窗-->
  <el-drawer v-model="editApiDlg"  :with-header="false" size="50%"><editApi ref="childRef" @closeDrawer="handleClose"  :interfaceData="interfaceData"  style="padding: 0 10px;"></editApi></el-drawer>

</template>

<script>
import {mapMutations, mapState} from "vuex";
import {ElNotification} from "element-plus";
import apiCite from '../../views/TestCase/apiCiteDlg.vue';
import Editor from'../../components/common/Editor.vue';
import editApi from '../../views/PerformanceTest/editApiDlg.vue';

export default {
  components:{
    apiCite,
    Editor,
    editApi
  },
  props: {
    scenceId: {
      type: Number,
      default: []
    },
    steps: {
      type: Array,
    },
    scenceData:{
      type: String,
    },
  },
  data() {
    return {
      addApiDlg:false,
      editApiDlg:false,
      selectType:'perf',
      treeKey: '',
      isExpand: false,
      ControllerData:{
        scence:'',
        name: '',
        type: '',
        content: {},
        desc:"",
        script:"",
        creator:'',
        weight: '',
      },
      step_id: '',
      interfaceData:'',
      options: [
          { value: 'equal', label: '等于' },
          { value: 'notEqual', label: '不等于' },
          { value: 'contains', label: '包含' },
          { value: 'notContains', label: '不包含' },
          { value: 'greaterThan', label: '大于' },
          { value: 'lessThan', label: '小于' },
          { value: 'greaterThanOrEqual', label: '大于等于' },
          { value: 'lessThanOrEqual', label: '小于等于' },
          { value: 'empty', label: '空' },
          { value: 'notEmpty', label: '非空' }
        ],

    }
  },
  methods: {

    rowOpenORFold(isExpand) {
	      this.treeKey = +new Date()
	      this.isExpand = isExpand
	    },

    handleStepClick(data) {
      if (data.stepInfo.type==='api'){
        this.editApiDlg = true;
        this.interfaceData = data.stepInfo;
      }
      else if(['for','script'].includes(data.stepInfo.type)) {
        data.stepInfo.dlg = !data.stepInfo.dlg;
      }
    },

    allowDrop(draggingNode, dropNode,type) {
      // 只有 type 为 api, for, if 的节点可以作为父级节点
      const allowedParentTypes = ['for', 'if'];
      if (!allowedParentTypes.includes(dropNode.data.stepInfo.type)) {
        return type === "prev" || type === "next";

      }else {
        return true
      };
  },

    fetchSteps(scenceId) {
      this.$emit('fetch-steps', scenceId);
    },

    async updateStepOrder() {
      const setParentIds = (node, parentId, parentSort) => {
        // 设置父节点的排序字段
        node.sort = parentSort;
        // 如果节点有子节点，则递归设置子节点的 parent 和排序字段
        if (node.children && node.children.length > 0) {
            node.children.forEach((child, childIndex) => {
                // 设置子节点的 parent 为当前节点的 id
                child.parent = node.id;
                // 设置子节点的排序字段
                child.sort = childIndex + 1;
                // 递归调用，处理子节点的子节点
                setParentIds(child, node.id, child.sort);
              });
            }
        };
      // 遍历步骤数组，设置父节点的排序字段和子节点的 parent 和排序字段
      this.steps.forEach((parent, parentIndex) => {
          // 设置父节点的排序字段
          parent.sort = parentIndex + 1;
          // 如果父节点有子节点，则设置子节点的 parent 和排序字段
          if (parent.children && parent.children.length > 0) {
              // 调用函数设置父节点和子节点的属性
              setParentIds(parent, parent.id, parent.sort);
          }else {
            parent.parent = null;
          }
      })
		},

    handleDragScroll() {
      document.addEventListener('mousemove', function(event) {
      const mouseY = event.clientY;
      const elementTop = document.querySelector('.el-tree').getBoundingClientRect().top;

      if (mouseY < 100 && elementTop > 0) {
        window.scrollBy(0, -10);
      } else if (mouseY > window.innerHeight - 100) {
        window.scrollBy(0, 10);
      }
    });
    },

    getCardIndex(parent, node) {
      const index = parent.childNodes.indexOf(node);
      return index + 1;
    },

    async addController(data, type) {
      const params = {...this.ControllerData};
      params.creator = this.username;
      params.type = type;
      params.scence = this.scenceId;
      const DataArray = [];
      let order_s = this.steps.length > 0 ? this.steps.length + 1 : 1;

      if(type ==='if'){
        params.name = "条件控制器";
        params.content = {
          variable:"",
          JudgmentMode:"",
          value:"",
        };
        delete params.weight;
      }
      else if(type ==='for'){
        params.name = "循环控制器";
        params.content = {
            select:"count",
            cycleIndex:"",
            cycleInterval:"",
            variable:"",
            variableName:""
          };
        delete params.weight;
      }
      else if(type ==='script'){
        params.name = "自定义脚本";
        delete params.weight;

      }
      else if(type ==='time'){
        params.name = "定时控制器";
        params.content = {
          time:""
        };
        delete params.weight;
      }
      else {
        params.name = 'HTTP接口';
        params.type = 'api';
        params.weight = 1;
        data.forEach(item => {
        let newItem = {
          ...params,
          content:item
        };
        DataArray.push(newItem);
      })
      }

      if (['if', 'for', 'time', 'script'].includes(type)) {
        const response = await this.$api.createScenceStep(params)
        if (response.status === 201) {
            this.step_id = response.data.id
        }
      }
      else {
        const response = await this.$api.createScenceStep(DataArray)
        if (response.status === 201) {
            this.step_id = response.data.map(item => item.id);
        }
      }
      const response = await this.$api.createTaskScenceStep({
        task: this.perfTask.id,
        scence: this.scenceId,
        step: this.step_id,
        sort: order_s,
        creator: this.username,
        parent: null,
      })
        if (response.status === 201) {
          ElNotification({
              duration: 500,
              title: '添加成功',
              type: 'success',
            })
        }
      this.fetchSteps(this.scenceId)
    },

    handleCloseModal() {
      this.addApiDlg = false;
    },
    clickApiDlg() {
      this.addApiDlg = true;
    },

    cancelEditing(data) {
      data.inputDlg = false;
    },

    startEditing(data) {
      if(data.type==='script'){data.inputDlg = true}else {data.inputDlg = true}
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },


    async delTree(data) {
      event.stopPropagation();
      console.log(data)
      const response = await this.$api.delTaskScenceStep(data.id,this.scenceId);
			if (response.status === 204) {
			  const res = await this.$api.delScenceStep(data.stepInfo.id);
			  if (res.status === 204){
          ElNotification({
              duration: 500,
              title: '删除成功',
              type: 'success',
            });
          this.fetchSteps(this.scenceId)
          }
			}
  },
   handleClose() {
      this.editApiDlg = false;
    },

  },
  computed: {
    ...mapState({
      envId: state => state.envId,
      testEnvs: state => state.testEnvs,
      pro: state => state.pro,
      perfTask: state => state.perfTask,
    }),
    defaultProps() {
      return {
        children: 'children',
        label: 'name',
      }
    },
    username() {
      return window.sessionStorage.getItem('username');
    },
  },
}

</script>

<style scoped>
.el-tag {
  color: #ffffff;
  width: 80px;
  height: 30px;
  text-align: center;
  font-size: 13px;
  line-height: 30px;

}
.pefStyle{
  margin-left: 8px;
  margin-top: 10px;
  margin-bottom: 10px;
  cursor: pointer;

}
.el-dropdown-menu__item {
  color: #606266;
  &:hover {
    background-color: #ebf5ff;
  }
}
.el-tree {
    --el-tree-node-hover-background-color: #ecf5ff;
    margin-right: 20px;
}
/deep/ .el-tree-node__content {
    padding: 3px 4px 3px 0px;
    height: auto;
}
.style {
    line-height: 11px;
    margin-bottom:6px
}
.card-title {
  display: flex;
  width: 1200px;
}
.card-content {
  float:right;
  justify-content: flex-end;
  margin-left: 50px;
  margin-top: -15px;
}

.card-name {
  font-size: 14px;
  margin-top: -6px;
}
.card-url {
  font-size: 15px;
  margin-top: -6px;
  margin-right: 10px;
}
.icon {
  display: inline-block;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  text-align: center;
  line-height: 28px;
  border: 2px solid;
  margin-left: -10px;
  margin-right: 6px;
  font-weight: normal;
}
.input-def{
  height: 20px;
  width: 180px;
  margin-right: 8px;
}
.el-input--small .el-input__inner {
    height: 27px;
    line-height: 32px;
}
.loop {
  margin: 10px 60px 10px 60px;
}
.script-button{
  color:black;
  border: none;
  outline: none;
  font-size: 15px;
}
.code_mod {
	margin-bottom: 5px;
}
.el-card {
  border-radius: 10px;
  --el-card-padding: 25px;
}
.custom-button .el-icon {
  margin-top: 10px; /* 调整箭头图标向下的距离 */
}
/deep/ .el-input--small .el-input__inner {
    height: 33px;
    line-height: 33px;
}
/deep/ .el-input--mini .el-input__inner {
    height: 30px;
    line-height: 30px;
}

</style>